package JSF;

import Entidades.AccDoc;
import Entidades.DocAdjunto;
import Entidades.Estado;
import Entidades.Expediente;
import Entidades.MovExp;
import Entidades.Trabajador;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionB.MovExpFacade;
import java.io.IOException;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.primefaces.context.RequestContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;

//*************************** fin PickList
@Named("movExpController")
@SessionScoped
public class MovExpController implements Serializable {

    private MovExp current;
    private MovExp movexp;
    private List<MovExp> lista;
    private List<MovExp> lista2;
    private List<DocAdjunto> lista3;
    private DataModel items = null;
    @EJB
    private SessionB.MovExpFacade ejbFacade;
    @EJB
    private SessionB.AccDocFacade ejbFacadeAccM;
    @EJB
    private SessionB.DocAdjuntoFacade ejbFacadeDocAdj;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String idregistro;
    private String fhhoy;
    private Trabajador trabajador;
    private String cadena_conexion = "jdbc:mysql://localhost:3306/emilima_tradoc";
    private String password = "carloscd3";
    private static Connection conn = null;
    private DualListModel<String> dualListModelAcc;
    private List<String> accSelec;
    private List<String> accAll;

    public MovExpController() {
        //Cities  
        //   List<AccDoc> accSelec = new ArrayList<AccDoc>();  
//        List<String> citiesSource = new ArrayList<String>();  
//        accSelec = new LinkedList<AccDoc>();
        accAll = new ArrayList<String>();
        accSelec = new ArrayList<String>();
        //      accAll = new ArrayList<AccDoc>();
        //    cities = new DualListModel<String>(citiesSource, citiesTarget);  
        dualListModelAcc = new DualListModel<String>(accAll, accSelec);
    }

    public MovExp getSelected() {
        if (current == null) {
            current = new MovExp();
            selectedItemIndex = -1;
        }
        return current;
    }

    private MovExpFacade getFacade() {
        return ejbFacade;
    }

    //----------------------------------------------------------------
    //-----------
    public DualListModel<String> getDualListModelAcc() {

        return dualListModelAcc;
    }

    public void setDualListModelAcc(DualListModel<String> dualListModelAcc) {
        this.dualListModelAcc = dualListModelAcc;
    }

    public List<String> getAccSelec() {
        return accSelec;
    }

    public void setAccSelec(List<String> accSelec) {
        this.accSelec = accSelec;
    }

    public List<String> getAccAll() {
        return accAll;
    }

    public void setAccAll(List<String> accAll) {
        this.accAll = accAll;
    }

    public String getFhhoy() {
        Date uDate = new Date(); //fecha actual
        long lnMilisegundos = uDate.getTime();
        java.sql.Date sqlDate = new java.sql.Date(lnMilisegundos);
        java.sql.Time sqlTime = new java.sql.Time(lnMilisegundos);

        Calendar hoy = Calendar.getInstance();
        //  SimpleDateFormat formateador = new SimpleDateFormat("yyyy-MM-dd");
        //          String ahora = formateador.format(hoy);
        int hdia = hoy.get(Calendar.DATE);
        int hmes = hoy.get(Calendar.MONTH) + 1;
        int hani = hoy.get(Calendar.YEAR);
        String ahora = String.valueOf(hdia) + "/" + String.valueOf(hmes) + "/" + String.valueOf(hani);
        String hora = sqlTime.toString();
        fhhoy = ahora + " " + " " + " " + hora;
        return fhhoy;
    }

    public void setFhhoy(String fhhoy) {
        this.fhhoy = fhhoy;
    }

    public Trabajador getTrabajador() {
        return trabajador;
    }

    public void setTrabajador(Trabajador trabajador) {
        this.trabajador = trabajador;
    }

    public MovExp getMovexp() {
        return movexp;
    }

    public void setMovexp(MovExp movexp) {
        this.movexp = movexp;
    }

    public List<MovExp> getLista() {
        return lista;
    }

    public void setLista(List<MovExp> lista) {
        this.lista = lista;
    }

    public String getIdregistro() {
        return idregistro;
    }

    public void setIdregistro(String idregistro) {
        this.idregistro = idregistro;
    }

  

    public void setLista3(List<DocAdjunto> lista3) {
        this.lista3 = lista3;
    }

//*************************** ini PickList    
//*********    
    public String fhoy() {

        Date uDate = new Date(); //fecha actual
        long lnMilisegundos = uDate.getTime();
        java.sql.Date sqlDate = new java.sql.Date(lnMilisegundos);
        java.sql.Time sqlTime = new java.sql.Time(lnMilisegundos);

        Calendar hoy = Calendar.getInstance();
        SimpleDateFormat formateador = new SimpleDateFormat("yyyy-MM-dd");
        String ahora = formateador.format(hoy);
        int hdia = hoy.get(Calendar.DATE);
        int hmes = hoy.get(Calendar.MONTH) + 1;
        int hani = hoy.get(Calendar.YEAR);
        System.out.println(" ahora " + ahora);
//                int vanio = Integer.parseInt(ahora.substring(0, 4));
//                int vmes = Integer.parseInt(ahora.substring(5, 7));
//                int vdia = Integer.parseInt(ahora.substring(8, 10));

        System.out.println("sql.Time: " + sqlTime);



        return null;
    }

    public void filtrar_nRegistro() {   // Filtra los Expedientes del Dia 
        System.out.println(" ------- En filtrar_nRegistro() ...");
        lista = new LinkedList<MovExp>();
        for (MovExp me : ejbFacade.findAll()) {
            //           System.out.println("me.getExpediente(). : "+me.getExpediente().getCodExp());  
            if (me.getExpediente().getCodExp().equals(idregistro)) {
//            if (v.getFechaReg().equals(fecha_emision)) { && v.getEstado().getIdEstado().equals("01")
                lista.add(me);
            }
        }

    }

    public void lista2yy() {   // Filtra los Expedientes del Dia 
        System.out.println(" ------- En filtrar_nRegistro() ...");
        lista = new LinkedList<MovExp>();
        ExpedienteController expctr = (ExpedienteController) JsfUtil.getManagedBean("ExpedienteController");
        idregistro = expctr.getExpedient().getCodExp();
        for (MovExp me : ejbFacade.findAll()) {
            //           System.out.println("me.getExpediente(). : "+me.getExpediente().getCodExp());  
            if (me.getExpediente().getCodExp().equals(idregistro)) {
//            if (v.getFechaReg().equals(fecha_emision)) { && v.getEstado().getIdEstado().equals("01")
                lista.add(me);
            }
        }

    }
//------------------ Report1 Movim de registros Derivados
    JasperPrint jasperPrint;

    public void initov() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = idregistro; //  expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);

            //    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfUser);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_Movim.jasper");
            //   jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSource);
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);

        } catch (Exception e) {
        }
    }

    public void reg_DerivaPrn(ActionEvent actionEvent) throws JRException, IOException {
        System.out.println(" Stoy en reg_DerivaPrn ................... ");
        initov();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //     httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");


        String fileNa = "Reg_HojaTram";
//            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + fileNa + "\"");

//        httpServletResponse.addHeader("Content-disposition", "inline");
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        //             httpServletResponse.addHeader("Content-disposition : inline" , "filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

//-------------------------------------- fin reporte    
//------------------ Report2 Movim de registros Derivados
//    JasperPrint jasperPrint;
    public void initov2() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = idregistro; //  expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_Movim2.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

    public void reg_DerivaPrn2(ActionEvent actionEvent) throws JRException, IOException {
        System.out.println(" Stoy en reg_DerivaPrn2 ................... ");
        initov2();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "Reg_Derivac2";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    //**************  reporte de Consulta Web  ******************************
    public void initov2w() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = idregistro; //  expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_Moviweb.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

    public void reg_DerivaPrnw(ActionEvent actionEvent) throws JRException, IOException {
        System.out.println(" Stoy en reg_DerivaPrn Web ................... ");
        initov2w();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "Reg_MoviWeb";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    //*************************************************************
    public String seekUser() throws IOException {
        //  HttpSession session = (HttpSession) FacesContext.getCurrentInstance();
        UsuarioController usuarioController = (UsuarioController) JsfUtil.getManagedBean("usuarioController");
        //    System.out.println(" ----- usuarioController es NULL NO hay Usuario logueado " + usuarioController);
        int idusu = usuarioController.getUsuario().getIdUsuario();
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
//        Query q = em.createQuery("SELECT t FROM Trabajador t join t.usuario u  WHERE u.idUsuario = :codtra Limit 1"); // jalar id de otra tabla
        Query q = em.createQuery("SELECT t FROM Trabajador t join t.usuario u  WHERE u.idUsuario = :codtra "); // jalar id de otra tabla
        q.setParameter("codtra", idusu);
        Trabajador trabajador;
        String page = null;
        trabajador = (Trabajador) q.getSingleResult();
        this.trabajador = trabajador;   // alamacena data del Trabajador en consulta
        Trabajador traba = new Trabajador();
        String idLogueo = this.getTrabajador().getIdResponsable();  //        System.out.println(" ---- user logueado " + idLogueo);
        if (idLogueo == null) {
            boolean loggedIn = false;
            loggedIn = false;
            FacesMessage msg = null;
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, " Usuario Inactivo", "Volder a Ingresar su Usuario y Password");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
            page = "logon?faces-redirect=true";
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().addCallbackParam("loggedIn", loggedIn);
            return page;
        }
        System.out.println(" ... idLogueo : " + idLogueo);
        return idLogueo;
    }

//-------------------------------------- fin reporte    
    public String eliminaDeriva() {
        try {
//*************************************  Compara si es el USER permitido para Eliminar  *****************************
            String idLogueoViene = seekUser();
            String idResp = movexp.getTrabajador().getIdResponsable(); //  System.out.println(" ----  user a eliminar : " + idResp);
//*******************************************************************************************************************
            if (idLogueoViene.trim() == idResp.trim()) {
                System.out.println(" ------ Antes de Eliminar ..");
                ejbFacade.remove(movexp);
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Eliminación Procesada ..!", "Registro Eliminado Correctamente");
                RequestContext.getCurrentInstance().showMessageInDialog(message);
            } else {

                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error de Usuario ..!", "NO estas Autorizado para Eliminar Registros de otro Usuario");
                RequestContext.getCurrentInstance().showMessageInDialog(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String grabaDeriva() {
        //    System.out.println(" ----------- String grabaderiva() ...................... ");
        // Recorrer todo las acciones seleccionadas y acumularlas en el campo Observaciones
        String accobs = " ";
        // Declaramos el Iterador e imprimimos los Elementos del ArrayList
        Iterator<String> nombreIterator = dualListModelAcc.getTarget().iterator();
//                 accSelec.iterator();
        while (nombreIterator.hasNext()) {
            String elemento = nombreIterator.next();
            accobs = accobs + elemento + ", ";
            System.out.print(elemento + " / ");
        }

//        String accobs3 = " ";
        UsuarioController usuarioController = (UsuarioController) JsfUtil.getManagedBean("usuarioController");
        int idusu = usuarioController.getUsuario().getIdUsuario();
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT t FROM Trabajador t join t.usuario u  WHERE u.idUsuario = :codtra "); // jalar id de otra tabla
        q.setParameter("codtra", idusu);
        Trabajador trabajador;
        String page = null;
        try {
            trabajador = (Trabajador) q.getSingleResult();
            this.trabajador = trabajador;   // alamacena data del Trabajador en consulta
            Trabajador traba = new Trabajador();
            traba.setIdResponsable(this.getTrabajador().getIdResponsable());
            //        System.out.println(" trabajador " + this.getTrabajador().getIdResponsable());
            movexp.setTrabajador(traba);
            Estado est = new Estado();
            est.setIdEstado("01");
            movexp.setEstado(est);
            movexp.setObservacion(accobs);
            //    movexp.setIdMovExp(9);
//            Trabajador traba = new Trabajador();
//            System.out.println("14");
//            traba.setIdResponsable(this.getTrabajador().getIdResponsable());
//            System.out.println("15");
//            movexp.setTrabajador(traba);
            // http://carloszuluaga.wikidot.com/articulos:manejo-de-fechas-en-java-i    
            Date utilDate = new java.util.Date();
            long lnMilisegundos = utilDate.getTime();
            Timestamp fechahora = new java.sql.Timestamp(lnMilisegundos);
            movexp.setFecha(fechahora);
//            String codgenerado = expedient.tipoTramite.sigla+expedient.interesArea.interesAreaPK.idInter+expedient.interesArea.interesAreaPK.idIntArea+expedient.interesArea.correla;
            //       codgen1 = expedient.getTipoTramite().getSigla().toString();
            //       codgen2 = expedient.getInteresArea().getInteresAreaPK().getIdInter().toString();
            //       codgen3 = expedient.getInteresArea().getInteresAreaPK().getIdIntArea().toString();
            //       codgen4 = expedient.getInteresArea().getCorrela().toString();
            //      expedient.setCodExp(codgen1 + codgen2 + codgen3 + codgen4);
            Expediente exped = new Expediente();
            exped.setCodExp(idregistro);
            movexp.setExpediente(exped);

            /*            System.out.println("Exp Id  " + movexp.getIdMovExp());
             System.out.println("Registro : " + movexp.getExpediente().getCodExp());
             System.out.println("Fecha " + movexp.getFecha());
             System.out.println("Asunto " + movexp.getAsunto());
             System.out.println("N Doc E " + movexp.getNumdocEmitido());
             System.out.println("Observac " + movexp.getObservacion());
             System.out.println("ResMd5  " + movexp.getResMd5());
             System.out.println("Anombre " + movexp.getArea().getIdarea());
             System.out.println("A1nombre " + movexp.getArea1().getIdarea());
             System.out.println("Estado " + movexp.getEstado());
             System.out.println("TipDoc " + movexp.getTipoDocInterno().getIdTipoDocInterno());
             System.out.println("Responsable " + movexp.getTrabajador().getIdResponsable());
             System.out.println("Folios " + movexp.getFolios());
             System.out.println(" --- ANtes de Grabar Derivacion ");
             */
            ejbFacade.create(movexp);
            filtrar_nRegistro();

            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(" Derivación Grabada exitosamente", "._."));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(" ----------- grabaDerivación Exception " + e);
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(" Error Al grabar Derivación ", "._."));
        }
        //       System.out.println("saliendo de grabar Derivación.................... ");
        return null;
    }

    public boolean mioEdito() {
        try {
            String usermio = seekUser();
            String usergrabo = movexp.getTrabajador().getIdResponsable();
            System.out.println(" modificar userMio : (" + usermio + ")");
            System.out.println(" modificar userGrab: (" + usergrabo + ")");

            if (usermio == usergrabo) {
                System.out.println(" true mio");
                return false;
            } else {
                System.out.println(" false mio");
                return true;
            }
        } catch (Exception e) {
            return false;
        }

    }

//----------------------------------------------------------------  fin   
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (MovExp) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public void prepareCreatecd() {
        movexp = new MovExp();
        current = new MovExp();
        System.out.println("----------- Stoy en PrepareCreatecd Deriva");

//-----  Prueba --------        
        accAll = new ArrayList<String>();
        AccDoc adoc = new AccDoc();
        for (AccDoc me : ejbFacadeAccM.findAll()) {
            String id = me.getIdAccDoc() + " - " + me.getNombre();
            System.out.println(" --- Id : " + id);
            adoc.setIdAccDoc(id);
//            adoc.setNombre(nombre);
            //       adoc.setNombre(me.getNombre());
            accAll.add(id);

        }
        dualListModelAcc = new DualListModel<String>(accAll, accSelec);
//------------              


    }

    public void prepareCreateEdita() throws IOException {
        boolean mioe = false;
        //     mioe = mioEdito();
        System.out.println(" ---- en prepareCreateEdita : " + mioe);
        //       if (mioe == true) {
        System.out.println("----------- Stoy en PrepareCreateEdita Deriva");
//--------------  Agrega Lista de Acciones YA Seleccionadas --------        
        accSelec = new ArrayList<String>();
        String val = "";
        String asigno = movexp.getObservacion() + ' ';
        for (int i = 0; i < asigno.length(); i++) {
            if (asigno.charAt(i) == ',' || i == asigno.length() - 1) {
                String[] valores = new String[4];
                int cont = 0;
                String va = "";
                for (int j = 0; j < val.length(); j++) {
                    if (val.charAt(j) == ',') {
                        valores[cont] = va;
                        cont++;
                        va = "";
                    } else {
                        va += "" + val.charAt(j);
                    }
                }
                va = va.trim();
                if (va.length() == 0) {
                    va = " ";
                } else {
                    System.out.println(" va : (" + va + ")");
                    accSelec.add(va);
                }
                val = "";
            } else {
                val += "" + asigno.charAt(i);
            }
        }
//**************************  Asigna Acciones Pendientes ***********************        
        accAll = new ArrayList<String>();
        AccDoc adoc = new AccDoc();
        int nume = 0;
        for (AccDoc me : ejbFacadeAccM.findAll()) {
            String id = me.getIdAccDoc() + " - " + me.getNombre();
            String idonly = me.getIdAccDoc().trim();
            String idele = null;
            nume = 0;
            int wi = 0;
            try {
                Iterator<String> nombreIterator = accSelec.iterator();
                while (nombreIterator.hasNext()) {
                    String elemento = nombreIterator.next().toString().trim();
                    idele = elemento.substring(0, 2);
                    if (idonly.equals(idele)) {
                        nume = 1;
                    }
                }
            } catch (Exception e) {
            }
            if (nume == 0) {
                accAll.add(id);
            }
            nume = 0;
            wi++;
        }
        dualListModelAcc = new DualListModel<String>(accAll, accSelec);
//------------
/*        } else {
         System.out.println(" Else no puede modificar registro de derivacion ....");
         FacesContext context = FacesContext.getCurrentInstance();
         context.addMessage(null, new FacesMessage(" No puede modificar Registro de otro Usuario", "Error : Sin Autorización"));
         }
         */


    }

    public String prepareCreate() {
        current = new MovExp();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovExpCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (MovExp) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() throws IOException {
//        try {
        String idLogueoViene = seekUser();
        String idResp = movexp.getTrabajador().getIdResponsable(); //  System.out.println(" ----  user a eliminar : " + idResp);
        System.out.println(" idLogueoViene : (" + idLogueoViene.trim() + ")");
        System.out.println(" idRespon      : (" + idResp.trim() + ")");
        if (idLogueoViene.trim() == idResp.trim()) {
            String accobs = " ";
            Iterator<String> nombreIterator = dualListModelAcc.getTarget().iterator();
            while (nombreIterator.hasNext()) {
                String elemento = nombreIterator.next();
                accobs = accobs + elemento + ", ";
            }
            movexp.setObservacion(accobs);
            current = movexp; // agreg
            getFacade().edit(current);
            System.out.println(" grabe ok");
//                FacesContext context = FacesContext.getCurrentInstance();
//                context.addMessage(null, new FacesMessage(" Registro Modificado exitosamente", "._."));

            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Modificación Procesada ...!", "Registro Modificado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);

            movexp = new MovExp();
            return null;
        } else {
//                 JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpedienteCreated"));
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("NoEditDeriva"));

//                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error de Usuario ..!", "NO esta Autorizado a Modificar Registros de otro Usuario");
//                RequestContext.getCurrentInstance().showMessageInDialog(message);
            System.out.println(" no puede modificar este user ");
            return null;
        }
        //     } catch (Exception e) {
        //         FacesContext context = FacesContext.getCurrentInstance();
        //         context.addMessage(null, new FacesMessage(" Error en Modificacion ", "-_-"));
        //         return null;
        //     }
    }

    public String updateOri() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovExpUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (MovExp) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovExpDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public MovExp getMovExp(java.lang.Integer id) {
//        String id1 = String.valueOf(id);
        return ejbFacade.find(id);


    }

    public List<MovExp> getLista2() {
        System.out.println(" ------- En getLista2() ...");
        lista2 = new LinkedList<MovExp>();
        ExpedienteController expctr = (ExpedienteController) JsfUtil.getManagedBean("expedienteController");
        idregistro = expctr.getExpedient().getCodExp();
        //       System.out.println(" ------------ Expe Selecc " + idregistro);
        if (idregistro == null) {
        } else {
            //----------
            //         EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
            //         EntityManager em = factory.createEntityManager();
            //         TypedQuery<MovExp> queryAll = em.createNamedQuery("MovExp.findIdExpedi", MovExp.class);
            //         lista2 = queryAll.getResultList();
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
            EntityManager em = factory.createEntityManager();
            String idExp = "";
            TypedQuery<MovExp> queryAll = em.createNamedQuery("MovExp.findIdExpedi", MovExp.class).setParameter("fkexp", idregistro);
            lista2 = queryAll.getResultList();
        }
//----------        
/*            for (MovExp me : ejbFacade.findAll()) {

         if (me.getExpediente().getCodExp().equals(idregistro)) {
         lista2.add(me);
         } else { //                    System.out.println(" --- Else . : " + me.getExpediente().getCodExp());
         }
         }*/
        getLista3();
    return lista2 ;
    }

public void setLista2(List<MovExp> lista2) {
        this.lista2 = lista2;
}

  public List<DocAdjunto> getLista3() {
        System.out.println(" ------- En getLista3() ...");
        lista3 = new LinkedList<DocAdjunto>();
        ExpedienteController derivaexp = (ExpedienteController) JsfUtil.getManagedBean("expedienteController");
        idregistro = derivaexp.getExpedient().getCodExp();
        //       System.out.println(" ------------ Expe Selecc " + idregistro);
        if (idregistro == null) {
        } else {
            //----------
         //   EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
         //   EntityManager em = factory.createEntityManager();
         //   TypedQuery<DocAdjunto> queryAll = em.createNamedQuery("DocAdjunto.findIdExped", DocAdjunto.class);
         //   lista3 = queryAll.getResultList();
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
            EntityManager em = factory.createEntityManager();
            TypedQuery<DocAdjunto> queryAll = em.createNamedQuery("DocAdjunto.findIdExpedien", DocAdjunto.class).setParameter("CodExp", idregistro);
            lista3 = queryAll.getResultList();
//----------        
        }
        return lista3;
    }

    @FacesConverter(forClass = MovExp.class)
public static class MovExpControllerConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            return null;
        }
        MovExpController controller = (MovExpController) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, "movExpController");
        return controller.getMovExp(getKey(value));
    }

    java.lang.Integer getKey(String value) {
        java.lang.Integer key;
        key = Integer.valueOf(value);
        return key;
    }

    String getStringKey(java.lang.Integer value) {
        StringBuilder sb = new StringBuilder();
        sb.append(value);
        return sb.toString();
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof MovExp) {
            MovExp o = (MovExp) object;
            return getStringKey(o.getIdMovExp());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + MovExp.class.getName());
        }
    }
}
}
